﻿const express = require('express');
const { randomBytes } = require('crypto');
const axios = require('axios');
const bodyParser = require('body-parser');
const cors = require('cors');


const app  = express();
app.use(bodyParser.json());
app.use(cors());


const posts = {

};

app.get('/',(req,res)=>{
    res.send(posts);
});

// Create a new post
app.post('/posts',  async (req,res)=>{
    const id = randomBytes(4).toString('hex');
    const { title } = req.body;

    posts[id] ={
        id,
        title,
    };

  await axios.post('http://localhost:4005/events',{
      type:'PostCreated',
      data:{
          id,
          title
      }
  });

    res.status(201).send(posts[id]);
});


app.post('/events',(req,res) =>{
   console.log('Received Event',req.body.type);

   res.send({});
});



app.listen(4000,()=>{
    console.log('Listening to 4000...')
});



